//
//  HJRoute.m
//  HJShop
//
//  Created by apple on 2019/4/16.
//  Copyright © 2019 HJShop. All rights reserved.
//

#import "HJRoute.h"
#import "TYBaseViewController.h"

@interface HJRoute ()
{
    NSMutableDictionary *routeMap;
}
@end

@implementation HJRoute
singleton_implementation(HJRoute)

- (void)registerController: (TYBaseViewController *)controller
{
    if (!routeMap) {
        routeMap = [NSMutableDictionary dictionary];
    }
    [routeMap setObject:NSStringFromClass(controller.class) forKey:controller.moudleName];
}

- (TYBaseViewController *)loadRoute:(NSString *)route
{
    if (route.length < 1) {
       return [TYBaseViewController new];
    }
    NSArray *pathComponents =  [route componentsSeparatedByString:@"?"];
    NSString *moudle = pathComponents[0];
    
    TYBaseViewController *controller = [TYBaseViewController new];
    NSString *className = [routeMap objectForKey:moudle];
    if (className && [className isKindOfClass:[NSString class]]) {
        controller = (TYBaseViewController *)[[NSClassFromString(className) alloc] init];
    }
    
    if (pathComponents.count > 1) {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        NSArray *args = [pathComponents[1] componentsSeparatedByString:@"&"];
        [args enumerateObjectsUsingBlock:^(NSString *item, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *content = [item componentsSeparatedByString:@"="];
            if (content.count > 1) {
                [params setObject:content[1] forKey:content[0]];
            }
        }];
        [controller setMoudleinfo:[params copy]];
    }
    
    return controller ? controller : [TYBaseViewController new];
}

@end
